<?php
// 应用公共文件

use app\common\service\AuthService;
use think\exception\HttpResponseException;
use think\facade\Cache;
use Firebase\JWT\JWT;
use app\admin\model\Users;
use app\admin\model\SalesDetail;
use app\admin\model\Sales;

if (!function_exists('__url')) {

    /**
     * 构建URL地址
     * @param string $url
     * @param array $vars
     * @param bool $suffix
     * @param bool $domain
     * @return string
     */
    function __url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        return url($url, $vars, $suffix, $domain)->build();
    }
}

if (!function_exists('password')) {

    /**
     * 密码加密算法
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     * @return mixed
     */
    function password($value)
    {
        $value = sha1('blog_') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }

}

if (!function_exists('xdebug')) {

    /**
     * debug调试
     * @param string|array $data 打印信息
     * @param string $type 类型
     * @param string $suffix 文件后缀名
     * @param bool $force
     * @param null $file
     */
    function xdebug($data, $type = 'xdebug', $suffix = null, $force = false, $file = null)
    {
        !is_dir(runtime_path() . 'xdebug/') && mkdir(runtime_path() . 'xdebug/');
        if (is_null($file)) {
            $file = is_null($suffix) ? runtime_path() . 'xdebug/' . date('Ymd') . '.txt' : runtime_path() . 'xdebug/' . date('Ymd') . "_{$suffix}" . '.txt';
        }
        file_put_contents($file, "[" . date('Y-m-d H:i:s') . "] " . "========================= {$type} ===========================" . PHP_EOL, FILE_APPEND);
        $str = (is_string($data) ? $data : ((is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true))) . PHP_EOL;
        $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
    }
}

if (!function_exists('sysconfig')) {

    /**
     * 获取系统配置信息
     * @param $group
     * @param null $name
     * @return array|mixed
     */
    function sysconfig($group, $name = null)
    {
        $where = ['group' => $group];
        $value = empty($name) ? Cache::get("sysconfig_{$group}") : Cache::get("sysconfig_{$group}_{$name}");
        if (empty($value)) {
            if (!empty($name)) {
                $where['name'] = $name;
                $value = \app\admin\model\SystemConfig::where($where)->value('value');
                Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}", $value, 3600);
            } else {
                $value = \app\admin\model\SystemConfig::where($where)->column('value', 'name');
                Cache::tag('sysconfig')->set("sysconfig_{$group}", $value, 3600);
            }
        }
        return $value;
    }
}

if (!function_exists('array_format_key')) {

    /**
     * 二位数组重新组合数据
     * @param $array
     * @param $key
     * @return array
     */
    function array_format_key($array, $key)
    {
        $newArray = [];
        foreach ($array as $vo) {
            $newArray[$vo[$key]] = $vo;
        }
        return $newArray;
    }

}

if (!function_exists('auth')) {

    /**
     * auth权限验证
     * @param $node
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function auth($node = null)
    {
        $authService = new AuthService(session('admin.id'));
        $check = $authService->checkNode($node);
        return $check;
    }
}

if (!function_exists('whereHook')) {
    /**
     * 强行非关联搜索where拦截器
     */
    function whereHook($data, $pk1, $model, $pk2)
    {
        switch (strtolower($data[1])) {
            case '=':
                $where[] = [$data[0], '=', $data[2]];
                break;
            case '%*%':
                $where[] = [$data[0], 'LIKE', "%{$data[2]}%"];
                break;
            case '*%':
                $where[] = [$data[0], 'LIKE', "{$data[2]}%"];
                break;
            case '%*':
                $where[] = [$data[0], 'LIKE', "%{$data[2]}"];
                break;
            case 'range':
                [$beginTime, $endTime] = explode(' - ', $data[2]);
                $where[] = [$data[0], '>=', strtotime($beginTime)];
                $where[] = [$data[0], '<=', strtotime($endTime)];
                break;
            default:
                $where[] = [$data[0], $data[1], "%{$data[2]}"];
        }
        $res = $model::where($where)->column($pk2);
        return [$pk1, 'in', $res];
    }
}

if (!function_exists('signToken')) {
    function signToken($uid, $hash){
        $key = config('jwt.salt');
        $token = [
            "iss"   =>  $key,
            "aud"   =>  '',
            "iat"   =>  time(),
            "nbf"   =>  time(),
            "exp"   =>  time() + config('jwt.expire'),
            "data"  =>  [
                'uid'       =>  $uid,
                'hash'      =>  $hash,
            ]
        ];
        $jwt = JWT::encode($token, $key, "HS256");
        return $jwt;
    }
}

if (!function_exists('checkToken')) {
    function checkToken($token){
        $key = config('jwt.salt');
        $status = ["code" => 2];
        try {
            JWT::$leeway = 60;
            $decoded = JWT::decode($token, $key, array('HS256'));
            $arr = json_decode(json_encode($decoded), true);
            $res['code'] = 0;
            $res['data'] = $arr['data'];
            return $res;
        } catch (\Firebase\JWT\SignatureInvalidException $e) {
            $status['msg'] = "token签名不正确";
            return $status;
        } catch (\Firebase\JWT\BeforeValidException $e) {
            $status['msg'] = "token失效";
            return $status;
        } catch (\Firebase\JWT\ExpiredException $e) {
            $status['msg'] = "token失效";
            return $status;
        } catch (Exception $e) {
            $status['msg'] = "token未知错误";
            return $status;
        }
    }
}

if (!function_exists('result')) {
    function result($code, $msg, $data = null, $status = 200){
        $data =  [
            'code'  =>  $code,
            'msg'   =>  $msg ?: '获取成功',
            'data'  =>  $data,
        ];
        throw new HttpResponseException(json($data, $status, $header = [
            'Access-Control-Allow-Headers'     => '*',
            'Access-Control-Allow-Origin'      => '*',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        ]));
    }
}

if (!function_exists('getJobNumber')) {
    function getJobNumber(){
        $max_job_number = \app\admin\model\Users::max('job_number');
        return $max_job_number + 1;
    }
}

if (!function_exists('formatJobNumber')) {
    function formatJobNumber($num){
        $len = strlen((string)$num);
        if ($len <= 6 ){
            return str_repeat('0',6 - $len).$num;
        }
        return $num;
    }
}

// 获取排名数据
if (!function_exists('ranking'))
{
    function ranking($type = 0, $length = 10, $month = null){
        $users = Users::where('status',0)->field('uid,true_name')->select();
        foreach ($users as $k => $user){
            $num = 0;
            $sales = Sales::where('uid', $user->uid)->select();
            foreach ($sales as $sale){
                if (in_array($type, [0,1])){
                    $num += SalesDetail::where('sales_id', $sale->id)->whereDay('create_time', $type ? 'yesterday' : 'today')->count();
                }else{
                    if (is_null($month)){
                        $num += SalesDetail::where('sales_id', $sale->id)->whereMonth('create_time')->count();
                    }else{
                        $num += SalesDetail::where('sales_id', $sale->id)->whereMonth('create_time', $month)->count();
                    }
                }
            }
            $users[$k]['num'] = $num;
        }
        $users = $users->toArray();
        foreach ($users as $k => $v){
            if (!$v['num']){
                unset($users[$k]);
            }
        }
        $num = array_column($users,'num');
        array_multisort($num, SORT_DESC, $users);
        if (count($users) < $length){
            $length = count($users);
        }
        $users = array_slice($users,0, $length);
        return $users;
    }
}

// 获取计算后的基本工资
if (!function_exists('getTrueBaseSalary'))
{
    function getTrueBaseSalary($user, $date1, $date2)
    {
        $entry_date = strtotime($user['entry_date']);
		if (time() - $entry_date > 30*24*60*60){
			return $user['base_salary'];
		}
        if ($date2 < $entry_date){
            return 0;
        }
        if ($date1 < $entry_date && $date2 > $entry_date){
            $date1 = $entry_date;
        }
        $num = ceil(($date2 - $date1)/86400);
        $base_salary = round($user['base_salary'] / 30 * $num,2);
        return $base_salary;
    }
}

// 过滤所有的空白字符（空格、全角空格、换行等）
if (!function_exists('myTrim'))
{
    function myTrim($str)
    {
        $search = array(" ","　","\n","\r","\t");
        $replace = array("","","","","");
        return str_replace($search, $replace, $str);
    }
}